import { QuestionCircleOutlined } from '@ant-design/icons';
import { Tooltip } from 'antd';
import classNames from 'classnames';
import React, { useContext } from 'react';
import type { YmColProps } from 'ym-design';
import { YmCol } from 'ym-design';
import FormLayoutContext from './Context/FormLayoutContext';
import type { FormLabelAlign } from './interface';
import type {
  FormItemLabelProps,
  LabelTooltipType,
  WrapperTooltipProps,
} from './interface/FormItemType';

function toTooltipProps(tooltip: LabelTooltipType): WrapperTooltipProps | null {
  if (!tooltip) {
    return null;
  }

  if (typeof tooltip === 'object' && !React.isValidElement(tooltip)) {
    return tooltip as WrapperTooltipProps;
  }

  return {
    title: tooltip,
  };
}

const FormItemLabel: React.FC<FormItemLabelProps> = (props) => {
  const { colon, htmlFor, label, labelAlign, labelCol, tooltip, required } =
    props;
  const {
    prefixCls,
    layout,
    labelWrap,
    labelAlign: contextLabelAlign,
    labelCol: contextLabelCol,
    colon: contextColon,
  } = useContext(FormLayoutContext);

  if (!label) return null;

  const mergedLabelAlign: FormLabelAlign = labelAlign ?? contextLabelAlign;
  const mergedLabelCol: YmColProps = labelCol || contextLabelCol || {};
  const labelClsBasic = `${prefixCls}-item-label`;
  const labelColClassName = classNames(
    labelClsBasic,
    mergedLabelCol.className,
    {
      [`${labelClsBasic}-left`]: mergedLabelAlign === 'left',
      [`${labelClsBasic}-wrap`]: !!labelWrap,
    },
  );
  let labelChildren = label;
  const haveColon = (colon ?? contextColon) === true && layout !== 'vertical';
  if (
    haveColon &&
    typeof label === 'string' &&
    (label as string).trim() !== ''
  ) {
    labelChildren = (label as string).replace(/[:|：]\s*$/, '');
  }

  // Tooltip
  const tooltipProps = toTooltipProps(tooltip);
  if (tooltipProps) {
    const { icon = <QuestionCircleOutlined />, ...restTooltipProps } =
      tooltipProps;
    const tooltipNode = (
      <Tooltip {...restTooltipProps}>
        {React.cloneElement(icon, {
          className: `${prefixCls}-item-tooltip`,
          title: '',
        })}
      </Tooltip>
    );

    labelChildren = (
      <>
        {labelChildren}
        {tooltipNode}
      </>
    );
  }
  const labelClassName = classNames({
    [`${prefixCls}-item-required`]: required,
    [`${prefixCls}-item-no-colon`]: !haveColon,
  });

  return (
    <YmCol {...mergedLabelCol} className={labelColClassName}>
      <label
        htmlFor={htmlFor}
        className={labelClassName}
        title={typeof label === 'string' ? label : ''}
      >
        {labelChildren}
      </label>
    </YmCol>
  );
};

export default FormItemLabel;
